//寄快递 => 快递公司选择

import React from "react"
import ReactDOM from "react-dom"
import template from "./ExpressCard.template.js"
import "./ExpressCard.less"

class ExpressCard extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            card_list: [{
                id: 1,
                name: "顺丰快递",
                price: "1",
                time: "3",
                img: "",
            }],
            selected_list: []
        }
    }
    componentWillMount() {
        this.setState({
            card_list: this.props.cardList,
            selected_list: this.props.selectedList || []
        })
    }
    componentWillReceiveProps(newProps) {
        this.setState({
            card_list: newProps.cardList
        })
    }

    pick(company_id) {
        return ()=>{
            let  {card_list, selected_list} = this.state
            const selected_id_list = selected_list.map(item=>item.id)
            //当前项在已选中列表中的索引
            const index = selected_id_list.indexOf(company_id)
            //当前项的内容
            let current_card 
            card_list.forEach(item=>{
                if(item.id === company_id) {
                    current_card = item
                }
            })
            if(index > -1) {
                selected_list.splice(index,1)
            }else {
                selected_list.push(current_card)
            }
            if(this.props.onChange) {
                this.props.onChange(selected_list)
            }
            this.setState({
                selected_list
            })
        }
    }

    render() {
        return template(this)
    }
}

module.exports = ExpressCard